package android.framework.widget.gallery;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Gallery;

/**
 * 自动滚动gallery 可以用作推荐，海报，广告
 * 
 * @ClassName: AutoScrollGallery
 * @Description: TODO
 * @author jtf19@163.com
 * @date 2013-7-23 下午3:23:11
 * 
 */
public class AutoScrollGallery extends Gallery {

	public AutoScrollGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	private static final int MSG_SLIDE = 1;
	private static final long PERIOD = 5000L;
	Handler handler = new Handler() {
		public void handleMessage(Message paramMessage) {
			super.handleMessage(paramMessage);
			switch (paramMessage.what) {
			case MSG_SLIDE:
				scrollToRight();
				break;
			}

		}
	};
	private boolean isAutoSlideMode;
	private float myX1;
	private float myX2;
	private TimerTask task = new TimerTask() {
		public void run() {
			Message localMessage = Message.obtain();
			localMessage.what = 1;
			handler.sendMessage(localMessage);
		}
	};
	private Timer timer = new Timer();

	private void scrollToLeft() {
		onScroll(null, null, -1.0F, 0.0F);
		super.onKeyDown(21, null);
	}

	private void scrollToRight() {
		onScroll(null, null, 1.0F, 0.0F);
		onKeyDown(22, null);
	}

	public void cancelAutoSlide() {
		if (this.timer == null)
			return;
		this.timer.cancel();
		this.timer = null;
	}

	public boolean onDown(MotionEvent paramMotionEvent) {
		if (this.isAutoSlideMode)
			cancelAutoSlide();
		this.myX1 = paramMotionEvent.getRawX();
		return super.onDown(paramMotionEvent);
	}

	public boolean onFling(MotionEvent paramMotionEvent1,
			MotionEvent paramMotionEvent2, float paramFloat1, float paramFloat2) {
		// this.myX1 = paramMotionEvent1.getRawX();
		this.myX2 = paramMotionEvent2.getRawX();
		if (this.myX2 - this.myX1 < 0.0F)
			scrollToRight();
		else if (this.myX2 - this.myX1 > 0.0F)
			scrollToLeft();
		if (!this.isAutoSlideMode)
			startAutoSlide();
		return false;
		// return super.onFling(paramMotionEvent1, paramMotionEvent2,
		// paramFloat1, paramFloat2);
	}

	public void startAutoSlide() {
		this.isAutoSlideMode = true;
		if (this.timer == null) {
			this.timer = new Timer();
			this.task = null;
			this.task = new TimerTask() {
				public void run() {
					Message localMessage = Message.obtain();
					localMessage.what = MSG_SLIDE;
					handler.sendMessage(localMessage);
				}
			};
		}
		this.timer.schedule(this.task, PERIOD, PERIOD);
	}
}
